import os
import json

from .stores import rebuild as mirros_rebuild, default_groups, autocomplete, search, get_pkginfo, filters
from .config import domain, port
from flask import Flask, render_template, redirect, request

cwd = os.path.dirname(__file__)

app = Flask(__name__, static_folder=f'{cwd}/dist')


@app.route('/rpm/')
def api_rpm():
    return render_template('rpm.html', param=get_pkginfo(request.args))


@app.route('/search/')
def api_search():
    target = request.args['q']
    filter = json.loads(request.args['filter'])

    return render_template('index.html', search=target, results=search(target, filter), filters=filters)


@app.route('/autocomplete/')
def api_autocomplete():
    target = request.args['q']
    filter = json.loads(request.args['filter'])
    return '["' + '","'.join(autocomplete(target, filter)) + '"]'


@app.route('/')
def root():
    return render_template('index.html', search='shadow-utils', results=default_groups, filters=filters)


@app.route('/rebuild')
def api_rebuild():
    mirros_rebuild()
    return redirect('/')


def main():
    app.run(host=domain, port=port, debug=False,)


if __name__ == "__main__":
    main()
